import { createVNode, provide, render, inject } from 'vue';

const createModalContextKey = () => Math.random().toString(36).substring(2);

const modalStack = new Map();

const processProps = (props) => {
  if (!props) {
    return {};
  }
  if (props instanceof Object) {
    return JSON.parse(JSON.stringify(props));
  }
  return {}
};
// 表单模态框hook
export function useFormModal() {
  const instance = getCurrentInstance();
  const getContext = () => {
    if (!instance) {
      throw new Error('useFormModal must be used within a component instance');
    }
    return instance.appContext;
  };
  const openModal = (component, props) => {
    return new Promise((resolve, reject) => {
      const _context = getContext();

      const contextKey = createModalContextKey();
      const container = document.createElement('div', { id: `modal-container-${contextKey}` });
      const close = () => {
        render(null, container);
        document.body.removeChild(container);
        modalStack.delete(contextKey);
      }
      modalStack.set(contextKey, {
        props: processProps(props),
        modalId: contextKey,
        resolve: (data = true) => {
          close();
          resolve(data);
        },
        reject: (err = 'cancel') => {
          close();
          reject(err);
        },
      });
      // 创建包装组件，确保每个模态框有独立的上下文
      const WrapperComponent = {
        setup() {
          provide("MODAL_CONTEXT", contextKey);
          return () => createVNode(component);
        }
      };

      // 创建vnode
      const vnode = createVNode(WrapperComponent);
      vnode.appContext = _context;
      // 渲染vnode
      render(vnode, container);
      // 添加到body
      document.body.appendChild(container);
    })
  }
  return {
    openModal
  }
}

export const useFormModalContext = () => {
  const contextKey = inject("MODAL_CONTEXT");
  if (!contextKey) {
    throw new Error('useModalContext must be used within a modal component');
  }
  const modalContext = modalStack.get(contextKey);
  if (!modalContext) {
    throw new Error('modalContext not found');
  }
  return {
    ...modalContext,
  };
}
